﻿using Consul;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Syspetro.DepConsul
{
    /// <summary>
    /// 权重
    /// </summary>
    public class WeightDispatcher : AbstractConsulDispatcher
    {
        #region Identity
        public WeightDispatcher(IConfiguration configuration) : base(configuration)
        {

        }
        #endregion

        protected override string ChooseAddress(string serviceName)
        {
            ConsulClient client = new(c =>
            {
                c.Address = new Uri(_ConsulClientOption.Address);
                c.Datacenter = base._ConsulClientOption.Datacenter;
            });
            AgentService agentService = null;
            var response = client.Agent.Services().Result.Response;

            this._CurrentAgentServiceDictionary = response.Where(s => s.Value.Service.Equals(serviceName, StringComparison.OrdinalIgnoreCase)).ToArray();
            if (this._CurrentAgentServiceDictionary.Length == 0)
            {
                throw new Exception("没有可用服务，请检查'VerifyUserUrl'是否正确配置");
            }

            var serviceDictionaryNew = new List<AgentService>();
            foreach (var service in base._CurrentAgentServiceDictionary)
            {
                serviceDictionaryNew.AddRange(Enumerable.Repeat(service.Value, int.TryParse(service.Value.Tags?[0], out int iWeight) ? 1 : iWeight));
            }
            int index = new Random(DateTime.Now.Millisecond).Next(0, int.MaxValue) % serviceDictionaryNew.Count;
            agentService = serviceDictionaryNew[index];

            return $"{agentService.Address}:{agentService.Port}";
        }
        /// <summary>
        /// 不需要了
        /// </summary>
        /// <returns></returns>
        protected override int GetIndex()
        {
            return 0;
        }
    }
}
